import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import './plugins/element.js'
import './common/css/common.css'
import './common/js/common.js'
import {request} from "./network/request";
import GFooter from './components/gfooter/GFooter'
import axios from "axios/index";

Vue.prototype.request = request;
Vue.config.productionTip = false

import mavonEditor from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'
Vue.use(mavonEditor)

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

window.addEventListener('popstate',function(e){
  router.isBack = true;
},false)

axios.interceptors.request.use(config => {
    //判断是否存在token，如果存在将每个页面header都添加token
    if(store.state.token){
        config.headers.common['Authorization'] = store.state.token
    }
    return config;
}, error => {

});

// http response 拦截器
axios.interceptors.response.use(
    response => {
        return response;
    },
    error => {
        if (error.response) {
            switch (error.response.data.message) {//若message为401则返回登录页
                case '401':
                    store.commit('delToken');
                    router.replace('/login');
            }
        }
    });

router.afterEach((to, from, next) => {
    window.scrollTo(0, 0)
});

router.beforeEach((to, from, next) => {
    if(to.path == '/login' || to.path == '/' ||to.path == '/register') {
        next();
    } else {
        let token = localStorage.getItem('token');
        if(token == undefined || token == '') {
            next('/');
        }else {
            next();
        }
    }
});